package org.zjx.core.state;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

// 增强的线程安全StateAccessor实现
public class ConcurrentStateAccessor implements StateAccessor {
    private final ConcurrentHashMap<Class<? extends StateComponent>, StateComponent> components;
    private final ReadWriteLock lock = new ReentrantReadWriteLock();


    public ConcurrentStateAccessor() {
        components = new ConcurrentHashMap<>();
    }

    public <T extends StateComponent> Optional<T> getComponent(Class<T> type) {
        lock.readLock().lock();
        try {
            StateComponent component = components.get(type);
            return Optional.ofNullable(type.cast(component));
        } finally {
            lock.readLock().unlock();
        }
    }

    @Override
    public Collection<StateComponent> getAllComponents() {
        return components.values();
    }

    public <T extends StateComponent> void registerComponent(Class<T> type, T component) {
        lock.writeLock().lock();
        try {
            components.put(type, component);
        } finally {
            lock.writeLock().unlock();
        }
    }

    @Override
    public <T extends StateComponent> void removeComponent(Class<T> type) {
        components.remove(type);
    }

    // 添加状态变更监听
    private final List<StateChangeListener> listeners = new CopyOnWriteArrayList<>();

    public void addListener(StateChangeListener listener) {
        listeners.add(listener);
    }

    public void notifyChange(Class<? extends StateComponent> type) {
        listeners.forEach(l -> l.onStateChanged(type));
    }


    public interface StateChangeListener {
        void onStateChanged(Class<? extends StateComponent> componentType);
    }
}
